package com.mywork.mvpkodeinxml.net

import com.mywork.mvpkodeinxml.common.SERVER_ADDRESS
import com.mywork.retrofitfileconverter.FileConverterFactory
import com.mywork.retrofitfileconverter.body.HttpClientHelper
import com.mywork.retrofitfileconverter.body.ProgressResponseListener
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory

object DownloadFactory {
    private val retrofit: Retrofit

    private var mListener: ProgressResponseListener? = null

    fun setListener(listener: ProgressResponseListener) {
        mListener = listener
    }

    val defaultListener: ProgressResponseListener = object : ProgressResponseListener {
        override fun onResponseProgress(bytesRead: Long, contentLength: Long, done: Boolean) {
            mListener?.onResponseProgress(bytesRead, contentLength, done)
        }
    }

    init {
        retrofit = Retrofit.Builder()
            .baseUrl(SERVER_ADDRESS)
            .addConverterFactory(FileConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(initClient(defaultListener))
            .build()
    }

    private fun initClient(listener: ProgressResponseListener): OkHttpClient {
        return HttpClientHelper.addProgressResponseListener(OkHttpClient.Builder(), listener).build()
    }

    fun <T> create(service: Class<T>): T {
        return retrofit.create(service)
    }

}